<?php
// https://paas.huifu.com/partners/api#/yhgl/api_yhgl_ywrz
namespace jy_huifuapi;
defined('BY_JYA') or exit('error');
class api extends \plugin{
    public function __construct($setting=array()){
        parent::__construct('jy_huifuapi');
        $setting=uni_setting('pay');
        if(!$setting['huifuapi_sysid'] || !$setting['huifuapi_productid'] || !$setting['huifuapi_private'] || !$setting['huifuapi_public']){
            exi('商户sysid，商户productid，商户私钥，汇付公钥，都必须填写','error');
        }
        if($_SESSION['auth_wxid']){
            $auth_appid=pdo_getcolumn('core_account_wechat',array('id'=>$_SESSION['auth_wxid']),'appid');
        }
        $wechat_appid=$auth_appid?:$setting['wechat_appid'];
        if(!$wechat_appid){
            $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid'],'isdefault'=>1),'appid');
            if(!$wechat_appid){
                $wechat_appid=pdo_getcolumn('core_account_wechat',array('uniacid'=>$_SESSION['uniacid']),'appid');
            }
        }
		if($_SESSION['wxapp_id'] && !$_SESSION['fromh5wxapp']){
			$wxapp=pdo_get('core_account_wxapp',array('uniacid'=>$_SESSION['uniacid'],'id'=>$_SESSION['wxapp_id']));
			$wxapp_appid=$wxapp['appid'];
		}
        $this->config=array(
            'sub_appid'=>$wxapp_appid?:$wechat_appid,
			'alipay_store_id'=>$alipay_store_id,
            'sys_id'=>$setting['huifuapi_sysid'],
            'product_id'=>$setting['huifuapi_productid'],
			'huifuapi_private'=>$setting['huifuapi_private'],
        );
    }
	public function getlog($mid=0,$setting=array(),$isexi=false){
		$setting=$setting?:plugin('jy_huifuapi')->plugin_setting('basic');
		$qianyue=pdo_get('core_member_bank',array('plugin_name'=>'jy_huifuapi','uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
		if($qianyue['passed']!=1 && $isexi){
			exi('还未签约不能提现！','error');
		}
		return $qianyue;
	}
	//开户
	public function openinfo($data=array()){
		$log=model('jy_huifuapi/model')->checklog($data['sn'].'X',2);
		if($log['id'] && $log['res']['huifu_id']){
			return $log['res']['huifu_id'];
		}
		$post_data=json_decode($data['post_data'],true);
		$cert_begin_date=$post_data['year1'].$post_data['month1'].$post_data['day1'];
		$cert_end_date=$post_data['year2'].$post_data['month2'].$post_data['day2'];
		$pcd=json_decode($data['pcd'],true);
		$prov_id=$this->get_area_code($pcd);
		$area_id=$this->get_area_code($pcd,1);
		$biz_content = array(
			"req_date" => date('Ymd', TIMESTAMP),
			"req_seq_id" =>$data['sn'].'X',
			"name" =>$data['realname'],
			'cert_type'=>'00',
			'cert_no'=>$data['cardnum'],
			'cert_validity_type'=>$post_data['timetype'],
			'cert_begin_date'=>$cert_begin_date,
			'cert_end_date'=>$cert_end_date,
			'mobile_no'=>$data['mobile'],
		);
        file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 开户记录:" .ijson_encode($biz_content)."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/user/basicdata/indv',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			exi('开户失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		model('jy_huifuapi/model')->uplog($res,$biz_content['req_seq_id'],2);
		return $res['huifu_id'];
    }
    //签约
    public function checkinfo($data=array()){
		$huifu_id=$this->openinfo($data);
		$log=model('jy_huifuapi/model')->checklog($data['sn'],3);
		if($log['id'] && $log['res']['passed'] && $log['createtime']>1715929546){
			$log['res']['passed']=1;
			return $log['res'];
		}
		$biz_content = array(
				"req_date" => date('Ymd', TIMESTAMP),
				"req_seq_id" =>$data['sn'],
				"huifu_id" =>$huifu_id,
				"upper_huifu_id" =>$this->config['sys_id'],
		);
		$settle_config=array(
			'fixed_ratio'=>'0.05',
			'workday_fixed_ratio'=>'0.05',
			'settle_cycle'=>'D1',
		);
		$biz_content['settle_config']=ijson_encode($settle_config);
		$post_data=json_decode($data['post_data'],true);
		$cert_begin_date=$post_data['year1'].$post_data['month1'].$post_data['day1'];
		$cert_end_date=$post_data['year2'].$post_data['month2'].$post_data['day2'];
		$pcd=json_decode($data['pcd'],true);
		$prov_id=$this->get_area_code($pcd);
		$area_id=$this->get_area_code($pcd,1);
		$card_info=array(
			'card_type'=>'1',
			'card_name'=>$data['realname'],
			'card_no'=>$data['bankcard'],
			'prov_id'=>$prov_id,
			'area_id'=>$area_id,
			'cert_type'=>'00',
			'cert_no'=>$data['cardnum'],
			'cert_validity_type'=>$post_data['timetype'],
			'cert_begin_date'=>$cert_begin_date,
			'cert_end_date'=>$cert_end_date,
		);
		$biz_content['card_info']=ijson_encode($card_info);
		$cash_config[]=array(
			'cash_type'=>'D1',
			'fix_amt'=>'0.02',
			'fee_rate'=>'0.02',
		);
		$biz_content['cash_config']=ijson_encode($cash_config);
		//$biz_content['cash_config']=ijson_encode($biz_content['cash_config']);
        file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 绑卡记录:" .ijson_encode($biz_content)."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/user/busi/open',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			if($res['resp_code']=='00000002'){
				pdo_delete('core_member_bank',array('uniacid'=>$_SESSION['uniacid'],'sn'=>$data['sn']));
			}
			exi('绑卡失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		$res['passed']=1;
		$res['userhuifu_id']=$huifu_id;
		model('jy_huifuapi/model')->uplog($res,$biz_content['req_seq_id'],3);
		return $res;
    }
	//提现
    public function tixian($data=array()){
		$this->zhuanfee($data);
		$log=pdo_get('core_member_bank',array('plugin_name'=>'jy_huifuapi','uniacid'=>$_SESSION['uniacid'],'mid'=>$data['mid']));
		if(!$log){
			exi('该用户！还未绑卡不能提现！','error');
		}
		if($log['passed']!=1){
			exi('该用户！未成功绑卡！','error');
		}
		$res_data=json_decode($log['res_data'],true);
		$token_no=$res_data['token_no'];
		if(!$token_no){
			exi('未成功绑卡！token_no不存在！','error');
		}
		$biz_content = array(
				"req_date" => date('Ymd', TIMESTAMP),
				"req_seq_id" =>$data['ordersn']?:$data['sn'],
				"huifu_id" =>$res_data['userhuifu_id'],
				"cash_amt" =>$data['money'],
				"into_acct_date_type" =>'D1',
				"token_no" =>$token_no,
				"notify_url" => $data['notify_url']?custom_url($data['notify_url'],true):SITEROOT .'addons/jy_huifuapi/notify.php',
		);
        file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 提现记录:" .ijson_encode($biz_content)."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/trade/settlement/enchashment',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			exi('提现失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		return res;
    }
	//转账https://paas.huifu.com/partners/api/#/yuer/api_acctpayzf
    public function zhuanfee($data=array()){
		$huifu_id=model('jy_huifuapi/model')->gethuifu_id($data['mid']);
		if(!$huifu_id){
			exi('该用户！还未开户！','error');
		}
		$sn=$data['ordersn']?:$data['sn'];
		$log=model('jy_huifuapi/model')->checklog('zhuan'.$sn,4);
		if($log['id'] && $log['res']['passed'] && $log['createtime']>1715929546){
			$log['res']['passed']=1;
			return $log['res'];
		}
		$biz_content = array(
				"req_date" => date('Ymd', TIMESTAMP),
				"req_seq_id" =>'zhuan'.$sn,
				"out_huifu_id" =>$this->config['sys_id'],
				"ord_amt" =>$data['money'],
				"good_desc" =>'提现先转账',
		);
		$acct_infos=array();
		$acct_infos[]=array('div_amt'=>$data['money'],'huifu_id'=>$huifu_id);
		$acct_split_bunch=array(
			'acct_infos'=>$acct_infos,
		);
		$biz_content['acct_split_bunch']=ijson_encode($acct_split_bunch);
		$risk_check_data=array(
			'transfer_type'=>'05',
		);
		$biz_content['risk_check_data']=ijson_encode($risk_check_data);
        file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 提现先转账记录:" .ijson_encode($biz_content)."\r\n", FILE_APPEND);
        $res=$this->request('https://api.huifu.com/v2/trade/acctpayment/pay',$biz_content);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 返回信息:" . ijson_encode($res)."\r\n", FILE_APPEND);
		if($res['resp_code']!='00000000' && $res['resp_code']!='00000100'){
			exi('转账失败原因:'.$res['resp_code'].$res['resp_desc'],'error');
		}
		$res['passed']=1;
		$res['userhuifu_id']=$huifu_id;
		model('jy_huifuapi/model')->uplog($res,$biz_content['req_seq_id'],4);
		return $res;
    }
	public function request($url,$post=null,$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$sign=$this->getSign($post);
		$apipost=array(
			'sys_id'=>$this->config['sys_id'],
			'product_id'=>$this->config['product_id'],
			'data'=>$post,
			'sign'=>$sign,
		);
		$post=ijson_encode($apipost);
		//file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . $url." request记录:" . $post."\r\n", FILE_APPEND);
		$rurl=$url;
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_json($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="请求, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		//print_r($result);exit;
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
			$message=$this->error_code($data['errcode']).' '.$data['errmsg'].' '.$data['errcode'];
			if($return_error || $_SESSION['this']=='custom'){
				//return error($message);
			}else{
				//exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
		    $message='请求错误，以下为原始数据：'.$result['content'];
    		if($return_error){
    			return error($message);
    		}else{
    			exi($message,'error');
    		}
		}
		$data=$data['data'];
		return $data;
	}
   /**
		 * 私钥加签（对数据源排序），可用于 V2 版本接口数据加签
		 *
		 * @param array $data 原数据( 排序后的json字符串; 数组参数排序后转json字符串(数据的中文和斜杠均不转码): 
									ksort($post_data); json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); )
		 *
		 * @param string $rsaPrivateKey 私钥
		 * @param int $alg 默认 OPENSSL_ALGO_SHA256
		 *
		 * @return string 签名串
	*/
    public function getSign($post_data=array(), $alg=OPENSSL_ALGO_SHA256){
		ksort($post_data); 
		$data=json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
		file_put_contents(ROOT_D.'/log.txt', date('Y-m-d H:i:s', time()) . " 签名串:" .$data."\r\n", FILE_APPEND);
		$rsaPrivateKey=$this->config['huifuapi_private'];
		$key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsaPrivateKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
		$signature= '';
		try {
			openssl_sign($data, $signature, $key, $alg);
		} catch (\Exception $e) {
			echo $e->getMessage();
		}
		return base64_encode($signature);
    }
	public function encrypt_data($biz_content_json='') {
		//分段加密方法
		$publicKey = $this->config['heepay_public'];
		// 要加密的数据
		$data = $biz_content_json;
		// 定义每个分段的大小
		$chunkSize = 117; // 2048-bit key can encrypt 117 bytes
		// 分段加密
		$encryptedData = '';
		for ($i = 0; $i < strlen($data); $i += $chunkSize) {
			$chunk = substr($data, $i, $chunkSize);
			openssl_public_encrypt($chunk, $encryptedChunk, $publicKey);
			$encryptedData .= $encryptedChunk;
		}
		// 将分段加密后的数据进行处理（例如Base64编码）并发送给接收方
		$encrypt_data = base64_encode($encryptedData);
		return $encrypt_data;
	}
	public function getdata($data1='') {
		$private_key_str=$this->config['huifuapi_private'];
		$encryptedData = base64_decode($data1);
		// 定义每个分段的大小
		$chunkSize = 256; // 2048-bit key can decrypt 256 bytes
		$PRIVATEkey=$private_key_str;
		// 分段解密
		$decryptedData = '';
		for ($i = 0; $i < strlen($encryptedData); $i += $chunkSize) {
			$chunk = substr($encryptedData, $i, $chunkSize);
			openssl_private_decrypt($chunk, $decryptedChunk, $PRIVATEkey);
			$decryptedData .= $decryptedChunk;
		}
		return $decryptedData;
	}
	public function get_area_code($area,$iscity=0){
		$address=$area['province'];
		$oldaddress=$area['province'];
		if($area['city'] && $iscity){
			$address.=' '.$area['city'];
			$oldaddress.=' 直辖市';
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address),'code');
		if(!$area_code){
			$isup=pdo_count('core_area',array(),'code');
			if(!$isup){
				require ROOT_D.'/update/update_area.php';
				$area_code=pdo_getcolumn('core_area',array('address'=>$address),'code');
			}else{
				$area_code=pdo_getcolumn('core_area',array('address'=>$oldaddress),'code');
				if(!$area_code){
					pdo_query('DROP TABLE IF EXISTS '.TABLE_PRE.'core_area;');
					require ROOT_D.'/update/update_area.php';
				}
			}
		}
		$area_code=mb_substr($area_code,0,6);
		return $area_code;
	}
}